package com.wsc.crawler.postcrawling;

import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
 
public class ConstructXML {
 
	private String xml;
	private Logger log=Logger.getLogger(ConstructXML.class.getName());
	
public String constructXML(List <String> listofurls){
 
	  try {
		  log.info("Constructing Xml file to post to frontier");
		  
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("urllist");
		
		doc.appendChild(rootElement);

		Iterator<String> itr= listofurls.iterator();
		
		while(itr.hasNext()){

		Element urlnode = doc.createElement("url");
		rootElement.appendChild(urlnode);
   
		// firstname elements
		URL url = null;
		String urlstring=null;
		try {
			urlstring =itr.next();
			url = new URL(urlstring);
		} catch (MalformedURLException e) {
		log.warn("Skipping URL because exception occured while adding ("+urlstring+") to XML file",e);	
			continue;
		}
		
		urlnode.appendChild(doc.createTextNode(url.toString()));
	  }
		
 		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
	     StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		
		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);
 
		transformer.transform(source, result);
		writer.flush();
		xml=writer.toString();
		log.debug("XML file Construction is completed.");
   
	  } catch (ParserConfigurationException pce) {
		log.warn("Exception occured :", pce);
	  } catch (TransformerException e) {
		  log.warn("Exception occured", e);
	}  
	  return xml;
	}
}